package com.tygz.interceptor;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.auto.base.pojo.SysUser;
import com.auto.common.SessionInfo;
import com.auto.util.SystemUtil;
import com.base.common.CommonConstants;
import com.base.util.JUtil;



public class AuthInterceptor implements HandlerInterceptor {

	private static final Logger logger = Logger.getLogger(AuthInterceptor.class);

	private static final String[] IGNORE_URI = {"sysManagelogin"};

	/**
	 * 完成页面的render后调用
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception {
	}

	/**
	 * 在调用controller具体方法后拦截
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 在调用controller具体方法前拦截
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {

		String requestPath = JUtil.getRequestPath(request);// 用户访问的资源地址
		//String v2hldghlcib0agugzgf0ysbhy2nlc3m = request.getParameter("v2hldghlcib0agugzgf0ysbhy2nlc3m");
		for(String url:IGNORE_URI){
			if(url.equals(requestPath)){
				return true;
			}
		}

		SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(CommonConstants.SESSION_MANAGE_USER);
		if (sessionInfo == null) {// 没有登录系统，或登录超时
			forward("您没有登录或登录超时，请重新登录！", request, response);
			return false;
		}

		if(!SystemUtil.getInstance().isContainsUrl(requestPath) && !SystemUtil.getInstance().isContainExtraPath(requestPath)){
			return true;
		}

		SysUser user = sessionInfo.getSysUser();
		if (user.getUserType() == 0) {// 超级管理员不需要验证权限
			return true;
		}
		
//		if(!JUtil.isNull(v2hldghlcib0agugzgf0ysbhy2nlc3m)  && "1".equals(v2hldghlcib0agugzgf0ysbhy2nlc3m.trim())){
//			//表示可以不加入到权限验证
//			return true;
//		}

		Set<String> allowUrls = sessionInfo.getAllowUrl();
		if (allowUrls.contains( requestPath) || SystemUtil.getInstance().isContainExtraPath(requestPath)) {// 验证当前用户是否有权限访问此资源
			return true;
		} else {
			forward("您没有权限访问，请联系管理员给您赋予相应权限！", request, response);
			return false;
		}

	}

	private void forward(String msg, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("msg", msg);
		String contextPath = request.getContextPath();
		//request.getRequestDispatcher(contextPath+"/jsp/other/error.jsp").forward(request, response);
		response.sendRedirect(contextPath+"/jsp/other/error.jsp");
	}

}
